<?php

namespace App\Providers;

use App\Services\ResponseService;
use Laravel\Lumen\Http\ResponseFactory;
use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        ResponseFactory::macro('success', function ($data) {
            if (is_object($data)) {
                $data = $data->toArray();
            }

            if (isset($data['data']) && isset($data['current_page'])) {
                $info['current_page'] = $data['current_page'];
                $info['total'] = $data['total'];
                $info['last_page'] = $data['last_page'];
                $info['per_page'] = $data['per_page'];
                if (isset($data['extras'])) {
                    $info = array_merge($info, $data['extras']);
                }
                $info['data'] = $data['data'];
            } else {
                $info = $data;
            }
            return response()->json(ResponseService::success($info))->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
